package com.eduplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eduplatform.common.Result;
import com.eduplatform.dto.SubjectDTO;
import com.eduplatform.entity.Subject;
import com.eduplatform.service.SubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/subjects")
@CrossOrigin
public class SubjectController {

    @Autowired
    private SubjectService subjectService;

    /**
     * 分页获取学科列表
     */
    @GetMapping("/list")
    public Result<Page<SubjectDTO>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam(value = "keyword", required = false) String keyword,
            @RequestParam(value = "level", required = false) Integer level) {

        // 创建分页对象
        Page<Subject> pageInfo = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getIsDeleted, 0); // 未删除

        // 按教育阶段筛选
        if (level != null) {
            queryWrapper.eq(Subject::getLevel, level);
        }

        // 关键字搜索
        if (keyword != null && !keyword.isEmpty()) {
            queryWrapper.like(Subject::getName, keyword);
        }

        // 排序
        queryWrapper.orderByDesc(Subject::getCreateTime);

        // 查询
        subjectService.page(pageInfo, queryWrapper);

        // 转换为DTO
        List<SubjectDTO> subjectDTOList = new ArrayList<>();
        for (Subject subject : pageInfo.getRecords()) {
            SubjectDTO subjectDTO = new SubjectDTO();
            BeanUtils.copyProperties(subject, subjectDTO);
            subjectDTOList.add(subjectDTO);
        }

        // 创建返回结果
        Page<SubjectDTO> subjectDTOPage = new Page<>();
        subjectDTOPage.setRecords(subjectDTOList);
        subjectDTOPage.setTotal(pageInfo.getTotal());
        subjectDTOPage.setCurrent(pageInfo.getCurrent());
        subjectDTOPage.setSize(pageInfo.getSize());

        return Result.success(subjectDTOPage);
    }

    /**
     * 获取所有学科（不分页）
     */
    @GetMapping("/all")
    public Result<List<SubjectDTO>> all(@RequestParam(value = "level", required = false) Integer level) {
        // 构建查询条件
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getIsDeleted, 0); // 未删除

        // 按教育阶段筛选
        if (level != null) {
            queryWrapper.eq(Subject::getLevel, level);
        }

        // 排序
        queryWrapper.orderByAsc(Subject::getLevel).orderByAsc(Subject::getName);

        // 查询
        List<Subject> subjects = subjectService.list(queryWrapper);

        // 转换为DTO
        List<SubjectDTO> subjectDTOList = new ArrayList<>();
        for (Subject subject : subjects) {
            SubjectDTO subjectDTO = new SubjectDTO();
            BeanUtils.copyProperties(subject, subjectDTO);
            subjectDTOList.add(subjectDTO);
        }

        return Result.success(subjectDTOList);
    }

    /**
     * 添加学科
     */
    @PostMapping("/add")
    public Result<Boolean> add(@RequestBody @Valid SubjectDTO subjectDTO) {
        // 检查学科名称是否已存在
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getName, subjectDTO.getName());
        queryWrapper.eq(Subject::getLevel, subjectDTO.getLevel());
        if (subjectService.count(queryWrapper) > 0) {
            return Result.error("该教育阶段下已存在同名学科");
        }

        // 创建学科
        Subject subject = new Subject();
        BeanUtils.copyProperties(subjectDTO, subject);

        // 设置创建时间和更新时间
        Date now = new Date();
        subject.setCreateTime(now);
        subject.setUpdateTime(now);

        // 设置未删除
        subject.setIsDeleted(0);

        // 保存
        boolean result = subjectService.save(subject);

        return Result.success(result);
    }

    /**
     * 更新学科信息
     */
    @PutMapping("/update")
    public Result<Boolean> update(@RequestBody @Valid SubjectDTO subjectDTO) {
        // 检查学科是否存在
        Subject existingSubject = subjectService.getById(subjectDTO.getId());
        if (existingSubject == null) {
            return Result.error("学科不存在");
        }

        // 检查学科名称是否已存在（排除自身）
        LambdaQueryWrapper<Subject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Subject::getName, subjectDTO.getName());
        queryWrapper.eq(Subject::getLevel, subjectDTO.getLevel());
        queryWrapper.ne(Subject::getId, subjectDTO.getId());
        if (subjectService.count(queryWrapper) > 0) {
            return Result.error("该教育阶段下已存在同名学科");
        }

        // 更新学科信息
        Subject subject = new Subject();
        BeanUtils.copyProperties(subjectDTO, subject);

        // 设置更新时间
        subject.setUpdateTime(new Date());

        // 更新
        boolean result = subjectService.updateById(subject);

        return Result.success(result);
    }

    /**
     * 删除学科
     */
    @DeleteMapping("/delete/{id}")
    public Result<Boolean> delete(@PathVariable Long id) {
        // 检查学科是否存在
        Subject existingSubject = subjectService.getById(id);
        if (existingSubject == null) {
            return Result.error("学科不存在");
        }

        // 逻辑删除
        boolean result = subjectService.removeById(id);

        return Result.success(result);
    }

    /**
     * 获取学科详情
     */
    @GetMapping("/detail/{id}")
    public Result<SubjectDTO> detail(@PathVariable Long id) {
        // 获取学科信息
        Subject subject = subjectService.getById(id);
        if (subject == null) {
            return Result.error("学科不存在");
        }

        // 转换为DTO
        SubjectDTO subjectDTO = new SubjectDTO();
        BeanUtils.copyProperties(subject, subjectDTO);

        return Result.success(subjectDTO);
    }
}